<?php

function smarty_resource_db_source($name, &$source, &$smarty) 
{
    list($name, $param) = smarty_resource_db_split($name);
    if (false !== ($value = smarty_resource_db_get($name, $param))) {
        $source = $value;
        return true;
    }
    return false;
}

function smarty_resource_db_timestamp($name, &$timestamp, &$smarty) 
{
    list($name) = smarty_resource_db_split($name);
    if (false !== ($value = smarty_resource_db_get($name, 'timestamp'))) {
        $timestamp = $value;
        return true;
    }
    return false;
}

function smarty_resource_db_secure($name, &$smarty) 
{
    // предполагаем, что шаблоны безопасны
    return true;
}

function smarty_resource_db_trusted($name, &$smarty) 
{
    // не используется для шаблонов
}

function smarty_resource_db_split($name) 
{
    return explode('.', $name, 2);
}

function smarty_resource_db_get($name, $param) 
{
    static $cache = array();
    if (!array_key_exists($name, $cache)) {
        $cache[$name] = smarty_resource_db__fetch($name);
    }
    return is_array($cache[$name]) ? $cache[$name][$param] : false;
}

function smarty_resource_db_defined($name, $param) 
{
    return strlen(smarty_resource_db_get($name, $param)) > 0;
}

function smarty_resource_db__fetch($name) 
{
    $query = 'SELECT
                     `subject`,
                     `text`,
                     `html`,
                     UNIX_TIMESTAMP(`timestamp`) AS `timestamp`
                FROM
                     `' . __postfix('system_template') . '`
               WHERE
                     `id` = "' . $name . '"';

    return database::fetchRow($query);
}
